<template>
  <div class="media">
    <div class="video-area">
      <video class="video" width="100%" height="auto" ref="video" autoplay :srcObject="videoSource">
        Video stream not available.
      </video>
      <canvas width="500" height="375" ref="canvas" id="canvas" />
      <img class="image" width="100%" height="100%" :src="photoSource" v-if="photoSource" />
    </div>


    <div class="button-container">
      <!-- 拍摄按钮 -->
      <button class="capture-button" @click="takePhoto">确认拍照</button>
      <!-- 重拍按钮 -->
      <button class="capture-button" @click="retakePhoto">重拍</button>
      <!-- 开始诊断按钮 -->
      <button class="capture-button" @click="startDiagnosis" :disabled="!photoSource">开始诊断</button>
    </div>

    <!-- 添加模态框 -->
    <div class="modal" @click="handleOutsideClick" v-if="isProcessing">
      <div class="modal-dialog" @click.stop>
        <div class="modal-content">
          <div class="modal-body">
            <p style="font-weight: bold; font-size:x-large;">请稍后在诊断结果中查看！</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import axios from 'axios';

export default {
  data() {
    return {
      url:{
        diagnose:'/palm/diagnose'
      },
      videoSource: null,
      photoSource: null,
      caseNo: localStorage.getItem("caseNo") || '', // 确保 caseNo 至少是一个空字符串
      // backendUrl: process.env.VUE_APP_BACKEND_URL || 'https://yzulcy.top/palm/diagnose', 
      isProcessing: false,
      cameraName: 'USB2.0 Camera RGB',
      // cameraName: 'HD Webcam',
      selectedCameraId: null, // 添加 selectedCameraId
      cameraDevice: null ,// 可能不需要这个变量，除非有其他用途
      gender: '',
      description: ''
    };
  },

  mounted() {
    this.initializeCamera();
  },

  methods: {
    selectGender(gender) {
      this.gender = gender; // 设置性别
    },
    async initializeCamera() {
      try {
        console.log('开始搜索摄像头');
        navigator.mediaDevices.getUserMedia({audio:true,video:true});
        const devices = await navigator.mediaDevices.enumerateDevices();
        const camera = devices.find(device => device.kind === 'videoinput' && device.label.includes(this.cameraName));
        // 打印所有设备信息以便调试
        console.log('Available devices:', devices);
        console.log('Available camera:', camera);

        // 筛选视频输入设备，找到与 cameraName 匹配的摄像头
        const targetCamera = devices.find(device => 
          device.kind === 'videoinput' && (device.label || '').includes(this.cameraName)
        );

        if (targetCamera) {
          this.selectedCameraId = targetCamera.deviceId;
          console.log(`Selected camera ID: ${this.selectedCameraId}, with label: ${targetCamera.label}`);
          await this.changeCamera();
        } else {
          console.error(`No video devices with the name "${this.cameraName}" found.`);
        }
      } catch (error) {
        console.error('Error initializing camera:', error);
      }
    },

    async changeCamera() {
      try {
        console.log('选择摄像头：', this.selectedCameraId);
        if (!this.selectedCameraId) return;
        const constraints = { video: { deviceId: { exact: this.selectedCameraId } }, audio: false };
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        console.log('Got stream:', stream);

        // 设置 video 元素的 srcObject
        this.$refs.video.srcObject = stream;
        // 有时候需要手动触发 play 事件
        this.$refs.video.play().catch(error => {
          console.error('Failed to play video:', error);
        });

        this.videoSource = stream;
      } catch (error) {
        console.error('Error accessing the camera:', error);
      }
    },

    takePhoto() {
      const canvas = this.$refs.canvas;
      const video = this.$refs.video;

      if (!canvas || !video) {
        console.error('Canvas or video is undefined.');
        return;
      }

      // 清除画布
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, 500, 375);

      // 将画布内容转换为数据URL
      this.photoSource = canvas.toDataURL('image/jpeg');
      console.log(this.photoSource);
    },

    retakePhoto() {
      this.photoSource = null;
    },

    async startDiagnosis() {
      try {
        this.isProcessing = true;
        // 确保 caseNo 存在且非空
        if (!this.caseNo || this.caseNo.trim() === '') {
          throw new Error('病历号(caseNo)不能为空！');
        }

        // 将数据URL转换为Blob
        const imageBlob = await this.dataUrlToBlob(this.photoSource);
        console.log('图片信息:', imageBlob);

        // 创建FormData对象
        const formData = new FormData();
        // 使用 caseNo 作为图片文件名
        formData.append('file', imageBlob, `${this.caseNo}.png`);
        formData.append('caseNo', this.caseNo); // 添加病历号到FormData
        // formData.append('gender', this.gender); 
        // formData.append('description', this.description); 


        console.log(`${this.URLhost}${this.url.diagnose}`)
        // 发送请求到后端
        const response = await axios.post(`${this.URLhost}${this.url.diagnose}`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        console.log('返回的诊断结果为:', response);

        // 更新诊断结果并保存到localStorage
        // const result = response.data.data.data;
        const reason = response.data.data.data.reason;
        const symptom = response.data.data.data.symptom;
        const method = response.data.data.data.method;
        localStorage.setItem('reason', reason);
        localStorage.setItem('symptom', symptom);
        localStorage.setItem('method', method); // 假设 result 是一个对象，需要序列化
        console.log('结果是:', localStorage.getItem('手诊'));

      } catch (error) {
        console.error('Error during diagnosis:', error);
        alert('诊断失败，请重试。');
      } finally {
        this.isProcessing = false;
      }
    },

    dataUrlToBlob(dataUrl) {
      return new Promise((resolve) => {
        const byteString = atob(dataUrl.split(',')[1]);
        const arrayBuffer = new ArrayBuffer(byteString.length);
        const uint8Array = new Uint8Array(arrayBuffer);

        for (let i = 0; i < byteString.length; i++) {
          uint8Array[i] = byteString.charCodeAt(i);
        }

        resolve(new Blob([uint8Array], { type: 'image/png' }));
      });
    },

    handleOutsideClick(event) {
      if (event.target === event.currentTarget) {
        this.isProcessing = false;
      }
    },
  },
};
</script>




<style scoped>
#app {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 定义媒体容器样式 */
.media {
  height: 95%;
  display: flex;
  flex-direction: column;
  /* 改为垂直排列 */
  /* gap: 1rem; */
  align-items: center;
}

/* 视频区域的最大宽度 */
.video-area {
  /* max-width: 100%; */
  /* height: 100%; */
  width: 60%;
  position: relative;

}

/* 视频和图像的边框圆角和溢出隐藏效果 */
.video {
  width: 100%;
  height: auto;
  border-radius: 8px;
  overflow: hidden;
  background-image: url('@/assets/image/图片预览.png');
  background-size: cover;
  background-position: center;
  border: 2px solid #d3d2d2;
}

/* 图片覆盖在视频上 */
.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  /* 使图片宽度为100%，以匹配视频宽度 */
  height: auto;
  /* 使图片高度为100%，以匹配视频高度 */
  object-fit: cover;
  /* 使图片填充整个容器，保持原始纵横比 */
  border-radius: 8px;
  /* 与视频相同的圆角 */
}

/* 按钮容器 */
.button-container {
  display: flex;
  width: 100%;
  justify-content: center;
  
  align-items: center;
}

/* 拍摄按钮样式 */
.capture-button {
  padding: 10px 20px;
  background-color: #007BFF;
  color: white;
  font-size: larger;
  font-weight: bold;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.1s ease;
  margin: 2%;
}

/* 悬停时改变按钮背景颜色 */
.capture-button:hover {
  background-color: #e1475e;
}

/* 隐藏Canvas元素 */
#canvas {
  display: none;
}


/* 模态框样式 */
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-dialog {
  background-color: #fff;
  margin: 15% auto;
  padding: 20px;
  border-radius: 5px;
  width: 30%;
  text-align: center;
}

.modal-body p {
  font-size: 16px;
  color: #333;
}

.input-container {
  margin-top: 1rem;
  width: 100%;
  text-align: center;
}

.gender-label {
  font-size: larger;
  font-weight: bold;
  margin-right: 1rem;
}

.gender-button {
  font-size: larger;
  font-weight: bold;
  padding: 1rem 2rem;
  margin: 0.5rem;
  background-color: #f0f0f0;
  border: 2px solid #d3d3d3;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.gender-button.active {
  background-color: #007bff;
  color: white;
  border-color: #0056b3;
}

.gender-button:hover {
  background-color: #e1475e;
  color: white;
}

textarea {
  width: 60%;
  height: 4rem;
  margin-top: 1rem;
  font-size: larger;
  padding: 0.5rem;
  border-radius: 8px;
  resize: none;
}

</style>